# encoding: utf-8
"""
文章标题
@author: xiao nian
@contact: xiaonian030@163.com
@date: 2022-09-08
"""

__copyright__ = "Copyright (c) (2022-2022) QF Inc. All Rights Reserved"
__author__ = "Xiao Nian"
__date__ = "2022-09-10:14:13:24"
__version__ = "1.0.0"

from gevent import monkey

monkey.patch_all()
import gevent
from dao.fans import get_task, get_list_for_normals, get_list_for_fails, patch_update, handle_result, get_users, \
    patch_update_users
from service.handle_image import download_image, get_hash_value, change_url
import base64
import hashlib
import shutil
import os

fail_id = 18446744073709551615
script_path = os.path.split(os.path.realpath(__file__))[0]
data_list = []


def f(url, main_id, name, task_id):
    global data_list
    try:
        name_base64 = str(base64.b64encode(str(name).encode('utf-8')), "utf-8")
    except:
        name_base64 = name
    url = change_url(url)
    if url == '':
        head_id = 0
        head_size = 0
    else:
        local_path = script_path + '/../data/image/' + str(task_id)
        try:
            local_file = download_image(url, local_path)
            head_id, head_size = get_hash_value(local_file, (6, 7))
        except:
            head_id = fail_id
            head_size = 0
    map_str = str(head_id) + '_' + name_base64 + '_' + str(head_size)
    map_id = hashlib.md5(map_str.encode(encoding='utf-8')).hexdigest()
    data_list.append((main_id, head_id, head_size, name_base64, map_id))


"""
批量处理头像
"""


def patch_header_image(patch_size):
    # 启动前处理数据 #
    task_ok, task_id, gh_id, table_name = get_task()
    if task_ok == 0:
        exit(0)

    # 开始任务 #
    global data_list
    last_id = 0
    task_error = 0
    while task_error == 0:
        spawn_list = []
        data_list = []
        try:
            head_list = get_list_for_normals(table_name, gh_id, last_id, patch_size)
            num = len(head_list)
            if num == 0:
                break
            last_id = int(head_list[num - 1][0])
            for item in head_list:
                head_url = item[1]
                main_id = int(item[0])
                name = item[2]
                spawn_list.append(gevent.spawn(f, head_url, main_id, name, task_id))

            # 批量下载头像
            gevent.joinall(spawn_list)
            patch_update(data_list)
        except:
            task_error = 1
        try:
            # 批量删除
            local_path = script_path + '/../data/image/' + str(task_id)
            shutil.rmtree(local_path, True)
        except:
            pass
    # 完成后处理数据 #
    handle_result(task_id)

    # 批量更新 #
    patch_update_user_ids(gh_id)
    return True


def patch_update_user_ids(gh_id_query=''):
    # 批量更新 #
    user_page = 1
    user_page_size = 5000
    pre_uni_id = ''
    map_index = 0
    while True:
        user_list = get_users(gh_id_query, user_page, user_page_size)
        num = len(user_list)
        if num == 0:
            break
        user_page = user_page + 1
        main_id_str = ''
        user_id_str = ''
        for item in user_list:
            gh_id = str(item[2])
            map_id = str(item[1])
            main_id = str(item[0])
            cur_uni_id = map_id + gh_id
            if pre_uni_id == '':
                pre_uni_id = cur_uni_id
                map_index = 0
                user_id = map_id + str(map_index)
            elif pre_uni_id != cur_uni_id:
                pre_uni_id = cur_uni_id
                map_index = 0
                user_id = map_id + str(map_index)
            else:
                map_index = map_index + 1
                user_id = map_id + str(map_index)
            if main_id_str == '':
                main_id_str = main_id
                user_id_str = 'WHEN ' + main_id + ' THEN "' + user_id + '"'
            else:
                main_id_str = main_id_str + ',' + main_id
                user_id_str = user_id_str + ' WHEN ' + main_id + ' THEN "' + user_id + '"'
        if main_id_str != '':
            patch_update_users(main_id_str, user_id_str)
    return True


def patch_header_image_fails(patch_size):
    global data_list
    last_id = 0
    task_error = 0
    task_id = fail_id
    while task_error == 0:
        spawn_list = []
        data_list = []
        try:
            head_list = get_list_for_fails(task_id, last_id, patch_size)
            num = len(head_list)
            if num == 0:
                break
            last_id = int(head_list[num - 1][0])
            for item in head_list:
                head_url = item[1]
                main_id = int(item[0])
                name = item[2]
                spawn_list.append(gevent.spawn(f, head_url, main_id, name, task_id))

            # 批量下载头像
            gevent.joinall(spawn_list)
            patch_update(data_list)

            # 批量更新 user id

        except:
            task_error = 1
        try:
            # 批量删除
            local_path = script_path + '/../data/image/' + str(task_id)
            shutil.rmtree(local_path, True)
        except:
            pass
